package com.ciwong.epaper.modules.epaper.ui.newlistenspeak.longcoversation;


import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.dbbean.LswAnswer;
import com.ciwong.epaper.modules.epaper.bean.Attachments;
import com.ciwong.epaper.modules.epaper.bean.ModuleSet;
import com.ciwong.epaper.modules.epaper.bean.OptionDetail;
import com.ciwong.epaper.modules.epaper.bean.QuestionRule;
import com.ciwong.epaper.modules.epaper.bean.Questions;
import com.ciwong.epaper.modules.epaper.bean.ResourceDetail;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.ui.newlistenspeak.BaseConversationActivity;
import com.ciwong.epaper.modules.epaper.ui.newlistenspeak.LsBottomView;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.ProgessBeakPoint;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class LongConversationActivity extends BaseConversationActivity {


    protected int mSmallQuesIndex = 0;// 当前小题下标
    protected int mChildQuesIndex = -1;// 当前子题下标


    public ScrollView container;
    protected ProgessBeakPoint bottomProgress;
    protected SeekBar seek_bar_make_score;
    protected TextView bottomNo;

    protected LongCoversataionQuestionLayout question_layout;
    private LongConversationBottomView ls_bottom_view;


    protected ListenSpeakUtil.State status = ListenSpeakUtil.State.START;
    protected int mQuestionType = Questions.QuestionType.QUESTION_TYPE_CHOICE;// 当前小题或子题类型，默认选择题


    protected int playCount;// 播放计数
    protected boolean isPlayAgain = false;// 是否是再一次播放
    protected boolean lookFlag = false;
    protected int mTimeCount;// 递减计时(秒)
    protected int mProgress;// seekbar的进度
    boolean isLastQues = false;
    private static final long PLAY_WAIT_TIME = 3000;// 多次播放间隔时间  // 播放附件音频
    //提前完成
    protected boolean mAheadRecord = false;
    private double mReadyTime;
    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (isFinishing()) {
                return;
            }
            int msgType = msg.what;
            switch (msgType) {
                case ListenSpeakUtil.HandlerWhat.UPDATE_TIME:// 倒计时更新时间 （准备时间倒计时，阅题倒计时，答题（录音）倒计时）
                    // 递减计时
                    if (mTimeCount > 0) {
                        mTimeCount--;
                        mProgress++;
                        removeMessages(ListenSpeakUtil.HandlerWhat.UPDATE_TIME);
                        int strResId = -1;
                        switch (status) {
                            case LOOK_SMALL_QUESTION:// 小题阅题
                            case LOOK_CHILD_QUESTION: // 子题阅题
                                strResId = R.string.look_question;
                                break;
                            case READY_SMALL_QUESTION:// 小题准备
                            case READY_CHILD_QUESTION:// 小题准备
                                strResId = R.string.ready_read;
                                break;
                            case ANSWER:
                                //选择题
                                //答题倒计时
                                strResId = R.string.answer_question;
                            default:
                                break;
                        }
                        if (strResId > 0) {

                            sendEmptyMessageDelayed(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, 1000);

                            Spannable span = new SpannableString(getString(R.string.tip_timer2, getString(strResId), String.valueOf(mTimeCount)));
                            span.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_light_green)), span.toString().indexOf("余") + 1, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            boolean isLastQues = false;
                            if (strResId == R.string.answer_question) {
                                isLastQues = isLastQuestion(mResourceDetail, mSmallQuesIndex);
                            }
                            if (strResId == R.string.answer_question) {
                                ls_bottom_view.updateTimer(span, mProgress, true, LsBottomView.SKIP_TYPE_CHOICE, status, isLastQues);
                            } else {
                                ls_bottom_view.updateTimer(span, mProgress, true, LsBottomView.SKIP_TYPE_COUNT_DOWN, status, false);
                            }
                        }

                    } else {// 计时结束
                        mAheadRecord = false;
                        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
                        try {
                            onTimeOver(status);
                        } catch (NullPointerException e) {

                        }
                    }
                    break;

                default:
                    break;
            }
        }

    };


    private boolean isNewVersion = true;
    private int mAudioViews = -1;
    private List<String> mAudioUrlList = new ArrayList<>();
    View.OnClickListener mSkipListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // 计时结束
            switch (status) {
                case BIG_QUESTION_STEM:
                    AudioPlayer.getInstance().stop();
                    break;
                case CHILD_QUESTION_STEM:// 单个子题题干播放完毕(连续播放附件内的音频)
                    ls_bottom_view.hideTimerAnimation(status);
                    // 播放计数
                    playCount--;
                    if (playCount > 0) {
                        isPlayAgain = true;
                        isShowTime = false;// 间隔时间内不需要显示倒计时
                        Message msg = new Message();
                        // 播放音频
                        msg.what = ListenSpeakUtil.HandlerWhat.PLAY_SOUND;
//                        msg.obj = audioUrl;
                        msg.obj= AudioPlayer.getInstance().getTag();
                        mRecorderHandler.sendMessageDelayed(msg, 300);// 播放附件音频

                    } else {
                        isPlayAgain = false;
                        playCount = mProgress = 0;
                        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.PLAY_SOUND, mRecorderHandler);
                        QuestionRule listeningAndSpeakingRule = mResourceDetail.getQuestions().get(mSmallQuesIndex).getListeningAndSpeakingRule();
                        startReady(listeningAndSpeakingRule.getReadyTime());

                        AudioPlayer.getInstance().stop();
                    }
                    break;
                default:
                    removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
                    mTimeCount = 0;
                    mAheadRecord = true;
                    onTimeOver(status);
                    break;
            }
        }
    };


    protected void onTimeOver(ListenSpeakUtil.State timeOverType) {
        //准备时间结束
        mProgress = mTimeCount = 0;
        ls_bottom_view.hideTimerAnimation(status);
        ls_bottom_view.setNextTipsVisibility(View.INVISIBLE);
        switch (timeOverType) {
            case LOOK_CHILD_QUESTION:// 子题阅题倒计时结束
                if (mReadyTime > 0) {
                    CWSys.setSharedBoolean(EConstants.SHARE_KEY_LSW_TIPS_READ + getUserInfoBase().getUserId(), true);
                }
                status = ListenSpeakUtil.State.CHILD_QUESTION_STEM;
                startLoadChildAudio();
                break;
            case READY_CHILD_QUESTION:// 子题准备倒计时结束
                if (mReadyTime > 0) {
                    CWSys.setSharedBoolean(EConstants.SHARE_KEY_LSW_TIPS_PREPARE + getUserInfoBase().getUserId(), true);
                }
                startAnswerQuestion();
                break;
            case ANSWER:// 答题结束
                CWLog.i(TAG, "答题/录音结束自动切换到下一题");

                if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_CHOICE) {
                    CWSys.setSharedBoolean(EConstants.SHARE_KEY_LSW_TIPS_ANSWER + getUserInfoBase().getUserId(), true);
                    Log.d("RemoveAllViews", "########ls_bottom_view.setStateBarVisibility(View.VISIBLE)#########");
                    ls_bottom_view.setStateBarVisibility(View.VISIBLE);
                    //提前结束答题不需要提示语
                    question_layout.allowAnswer(false);
                    if (mAheadRecord) {
                        mAheadRecord = false;
                        autoSwitchNextQuestion(mResourceDetail);
                    } else {
                        status = ListenSpeakUtil.State.END_AUDIO;
                        ls_bottom_view.setAnswerState(false);
                        // 答题结束提示语
                        printState();
                        AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_END_ANSWER, LongConversationActivity.this, null);
                    }
                }
                break;
            default:
                break;
        }

    }

    private OnPlayListener playListener = new OnPlayListener() {
        @Override
        public void stop(Object audioUrl) {
            if (isFinishing() || isStopHandle) {
                return;
            }
            //设置播放按钮状态
            ls_bottom_view.setPlayBtnState(false);
            Questions smallQuestion = mResourceDetail.getQuestions().get(mSmallQuesIndex);
            switch (status) {
                case START:
                    ls_bottom_view.setVisibility(View.VISIBLE);
                    startLoadBigQuestion(mResourceDetail);
                    break;
                case BIG_QUESTION_STEM:// 单个大题题干音频播放完毕（重复播放同一音频）
                    CWSys.setSharedBoolean(EConstants.SHARE_KEY_LSW_TIPS_PLAY + getUserInfoBase().getUserId(), true);
                    onBigStemPlayOver();
                    break;
                case SMALL_QUESTION_STEM:// 单个小题题干播放完毕(连续播放附件内的音频)
                case CHILD_QUESTION_STEM:// 单个子题题干播放完毕(连续播放附件内的音频)
                    ls_bottom_view.hideTimerAnimation(status);
                    // 播放计数
                    playCount--;
                    if (playCount > 0) {
                        isPlayAgain = true;
                        isShowTime = false;// 间隔时间内不需要显示倒计时
                        Message msg = new Message();
                        // 播放音频
                        msg.what = ListenSpeakUtil.HandlerWhat.PLAY_SOUND;
                        msg.obj = audioUrl;
                        mRecorderHandler.sendMessageDelayed(msg, 300);// 播放附件音频

                    } else {
                        isPlayAgain = false;
                        playCount = mProgress = 0;
                        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.PLAY_SOUND, mRecorderHandler);
                        QuestionRule listeningAndSpeakingRule = mResourceDetail.getQuestions().get(mSmallQuesIndex).getListeningAndSpeakingRule();
                        startReady(listeningAndSpeakingRule.getReadyTime());
                    }
                    break;
                case READY_CHILD_QUESTION:
                    startAnswerQuestion();
                    break;
                case ANSWER:// 开始答题/录音音频播放完毕
                    mTimeCount = smallQuestion.getListeningAndSpeakingRule().getAnswerTime();// 取得答题时间
                    ls_bottom_view.seekBarSetMax(mTimeCount);
                    mProgress = 0;
                    //题目类型:选择题
                    if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_CHOICE) {
                        startAnswerTimeCount();
                    }
                    break;
                case END_AUDIO:// 录音结束音频播放完毕
                    if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_CHOICE
                    ) {
                        autoSwitchNextQuestion(mResourceDetail);
                    } else {
                    }
                    break;
                case END:// 结束
                    setResultAnswer(getConversitionAnswer(), mBigQuesIndex + 1, false, false, true, totalQuesIndex);
                    break;
                default:
                    break;
            }


        }

        @Override
        public void onPlaying(long duration, long progress) {
            if (isFinishing()) {
                return;
            }

            int remainCount;
            Spannable span;
            switch (status) {
                case BIG_QUESTION_STEM:
                    mProgress = (int) progress;
                    // 更新时间
                    remainCount = (int) (duration - progress) / 1000;
                    span = new SpannableString(getString(R.string.tip_timer2, getString(isPlayAgain ? R.string.tip_play_again : R.string.tip_play), remainCount + ""));
                    span.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_light_green)), span.toString().indexOf("余") + 1, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    ls_bottom_view.updateTimer(span, 0, true, LsBottomView.SKIP_TYPE_PLAY_STEM, status, false);
                    break;
                case SMALL_QUESTION_STEM:
                case CHILD_QUESTION_STEM:
                    if (isShowTime) {
                        mProgress = (int) progress;
                        ls_bottom_view.seekBarSetMax((int) duration);
                        // 更新时间
                        remainCount = (int) (duration - progress) / 1000;
                        span = new SpannableString(getString(R.string.tip_timer2, getString(isPlayAgain ? R.string.tip_play_again : R.string.tip_play), remainCount + ""));
                        span.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_light_green)), span.toString().indexOf("余") + 1, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        ls_bottom_view.updateTimer(span, mProgress, true, LsBottomView.SKIP_TYPE_NULL, status, false);
                    }
                    break;

                default:
                    break;
            }
        }

        @Override
        public void onError(int i, Object arg1) {
            if (isFinishing()) {
                return;
            }
            ToastUtil.INSTANCE.toastCenterError(R.string.play_audio_fail);
            playListener.stop(arg1);
        }

        @Override
        public void onBuffer(Object o, long l, long l1) {

        }


        @Override
        public void onReadPlayer(long l, Object o) {

        }

        @Override
        public void onPlayStart(Object o) {

        }
    };


    @Override
    protected int setView() {
        return R.layout.activity_long_coversation;
    }

    @Override
    protected void findViews() {
        super.findViews();
        container = (ScrollView) findViewById(R.id.ls_container);
        question_layout = (LongCoversataionQuestionLayout) findViewById(R.id.question_layout);
        if (isNewVersion) {
            question_layout.setTitleVisibility(View.GONE);
        }
        ls_bottom_view = (LongConversationBottomView) findViewById(R.id.ls_bottom_view);
        bottomProgress = (ProgessBeakPoint) findViewById(R.id.bottom_progress);
        bottomNo = (TextView) findViewById(R.id.bottom_no);
        seek_bar_make_score = (SeekBar) findViewById(R.id.seek_bar_make_score);

    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ls_bottom_view.setOnSkipListener(mSkipListener);

    }

    @Override
    protected void init() {
        super.init();
        AudioPlayer.getInstance().setOnPlayListener(playListener);
    }

    @Override
    protected void loadData() {
//		getExamData();
        if (mResourceDetail != null) {
            final ModuleSet moduleSet = mResourceDetail.getTemplateSettings();// 大题模块设置
            if (moduleSet != null) {
                //考试开始预先加载大题和选项
                question_layout.initBigQuestionAndOptions(mResourceDetail, mBigQuesIndex, mSmallQuesIndex);
            }
            if (mIsPlayStartExamAduio) {
                ls_bottom_view.setVisibility(View.GONE);
                status = ListenSpeakUtil.State.START;
                AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_START_EXAM, mActivity, null);
            } else {
                startLoadBigQuestion(mResourceDetail);
            }

        }
    }

    public void getExamData() {
        //获取作业资源
        String path = ESystem.getProjectFolderPath(LongConversationActivity.this) + File.separator + "select2.txt";
        EpaperDao.getInstance().getSerializableObjects(path,
                ResourceDetail.class, new BaseExtCallBack(LongConversationActivity.this) {

                    @Override
                    public void success(final Object data) {
                        super.success(data);
                        mResourceDetail = (ResourceDetail) data;
                        if (mResourceDetail != null) {
                            final ModuleSet moduleSet = mResourceDetail.getTemplateSettings();// 大题模块设置
                            if (moduleSet != null) {
                                //考试开始预先加载大题和选项
                                question_layout.initBigQuestionAndOptions(mResourceDetail, mBigQuesIndex, mSmallQuesIndex);
                            }
                            startLoadBigQuestion(mResourceDetail);
                        }
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);

                    }

                    @Override
                    public void failed(Object data) {


                    }
                }

        );
    }


    /**
     * 开始播放大题音频
     * // 进入播放大题题干状态
     */
    protected void startLoadBigQuestion(ResourceDetail resourceDetail) {
        // 进入播放大题题干状态
        status = ListenSpeakUtil.State.BIG_QUESTION_STEM;
        printState();
        if (resourceDetail != null) {
            ModuleSet moduleSet = resourceDetail.getTemplateSettings();

            //用户可选择设置可以选择不播放大题题干
            if (isReadBigQuestionStem) {
                AudioPlayer.getInstance().play(ESystem.formatPath(moduleSet.getAudioUrl()));// 大题题干音频
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                    MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                    if (mMediaPlayer != null) {
                        try {
                            PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                            if (params != null) {
                                mMediaPlayer.setPlaybackParams(params);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                ls_bottom_view.showPlayButton(mQuestionType);
                //大题题干高亮
                question_layout.setBigStemHighLight(true);
            } else {
                onBigStemPlayOver();
            }

        }
    }


    private void onBigStemPlayOver() {
        //题干不高亮，内容高亮
        question_layout.setBigStemHighLight(false);
        Questions questions = null;
        if (null != mResourceDetail.getQuestions() && mSmallQuesIndex < mResourceDetail.getQuestions().size()) {
            questions = mResourceDetail.getQuestions().get(mSmallQuesIndex);
        }
        startLoadSmallQuestion(mResourceDetail, questions);
    }


    /**
     * 开始加载小题题干和附件
     *
     * @param question
     */
    protected void startLoadSmallQuestion(ResourceDetail resourceDetail, Questions question) {
        status = ListenSpeakUtil.State.SMALL_QUESTION_STEM;
        printState();
        OptionDetail optionsDetail = question.getTrunk();
        //增加小题序号
        String textTitle;
        String textScore = ListenSpeakUtil.getChildQuestionScore(question, resourceDetail.getScores());
        if (question.getSort() != null && !"".equals(question.getSort())) {
            textTitle = question.getSort() + "、" + textScore + optionsDetail.getBody();
        } else {
            textTitle = optionsDetail.getBody();
            if (!"".equals(textTitle)) {
                if (!"".equals(textScore)) {
                    StringBuffer stringBuffer = new StringBuffer(textTitle);
                    stringBuffer.insert(2, textScore);
                    textTitle = stringBuffer.toString();
                }
            } else {
                textTitle = textScore;
            }
        }
        question_layout.setSmallQuestionStem(textTitle);
        question_layout.startLoadImg(optionsDetail, ls_bottom_view.getSeekBarView());
        QuestionRule listeningAndSpeakingRule = question.getListeningAndSpeakingRule();
        if (listeningAndSpeakingRule != null) {
            int rootAudioViews = listeningAndSpeakingRule.getAudioViews();// 音频播放次数
            int lookTime = listeningAndSpeakingRule.getLookTime();
            startLoadAttachments(optionsDetail, rootAudioViews, 0,
                    lookTime, true);
            //开始进入子题或开始阅题
            startLoadChildQuestion(resourceDetail, mUuid);
            startLookQuestion(lookTime);
        }


    }


    /**
     * 移除Handler消息
     *
     * @param what
     */
    protected void removeHandlerMsg(int what, Handler mHandler) {
        if (mHandler.hasMessages(what)) {
            mHandler.removeMessages(what);
        }
    }


    /**
     * 开始加载附件
     *
     * @param optionsDetail
     * @param audioViews    音频播放次数
     * @param lookTime      看题时间
     * @param readyTime     准本时间
     * @param isSmallReady  是否来自
     */
    protected void startLoadAttachments(OptionDetail optionsDetail,
                                        int audioViews, int lookTime, int readyTime,
                                        boolean isSmallReady) {
        // 取附件集合
        final List<Attachments> attachmentsList = optionsDetail
                .getAttachments();
        List<String> audioUrlList = new ArrayList<String>();
        if (attachmentsList != null && !attachmentsList.isEmpty()) {
            // 取出所有的图片或语音地址
            for (int i = 0; i < attachmentsList.size(); i++) {
                Attachments attachments = attachmentsList.get(i);
                if (attachments != null) {
                    String url = attachments.getUrl();
                    if (!TextUtils.isEmpty(url)) {
                        switch (attachments.getFileType()) {
                            case Attachments.AttachmentFileType.ATTACHMENT_FILE_TYPE_AUDIO:// 语音
                                audioUrlList.add(ESystem.formatPath(url));
                                break;
                        }
                    }
                }
            }
            if (!audioUrlList.isEmpty()) {
                //播放附件里的语音,长对话的录音
                mAudioViews = audioViews;
                mAudioUrlList = audioUrlList;
            } else {
                mAudioViews = -1;
                mAudioUrlList.clear();
            }

        } else {
            mAudioViews = -1;
            mAudioUrlList.clear();
        }
    }


    public void startLoadChildAudio() {
        if (mAudioUrlList.size() > 0) {
            loadAttachmentsAudio(mAudioViews, mAudioUrlList);
        } else {
            startReady(mResourceDetail.getQuestions().get(mSmallQuesIndex).getListeningAndSpeakingRule().getReadyTime());
        }

    }

    /**
     * 播放附件里的语音
     * 播放第一个附件音频
     */
    protected void loadAttachmentsAudio(int audioViews, List<String> audioUrlList) {
        if (audioViews != -1) {
            playCount = audioViews;
        }
        lookFlag = true;
        ls_bottom_view.showPlayButton(mQuestionType);
        isPlayAgain = false;
        AudioPlayer.getInstance().play(audioUrlList.get(0));// 播放第一个附件音频
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                if (mMediaPlayer != null) {
                    try {
                        PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                        if (params != null) {
                            mMediaPlayer.setPlaybackParams(params);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        printState();
    }

    /**
     * 开始准备倒计时
     * 发送更新时间消息
     *
     * @param readyTime
     */
    protected void startReady(int readyTime) {
        playCount = 0;
        status = ListenSpeakUtil.State.READY_CHILD_QUESTION;
        printState();
        // 进入准备状态
        mTimeCount = readyTime;
        mProgress = 0;
        ls_bottom_view.seekBarSetMax(mTimeCount);
        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
        mHandler.sendEmptyMessage(ListenSpeakUtil.HandlerWhat.UPDATE_TIME);
    }

    /**
     * 开始阅题
     */
    protected void startLookQuestion(int lookTime) {
        question_layout.allowAnswer(true);
        ls_bottom_view.microRecordingSetVisibility(View.GONE);
        status = ListenSpeakUtil.State.LOOK_CHILD_QUESTION;
        playCount = 0;
        //        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.PLAY_SOUND, mHandler);
        // 进入阅题状态
        mTimeCount = lookTime;
        mReadyTime = lookTime;
        printState();
        mProgress = 0;
        //        ls_bottom_view.updateTimer(null, progress,true,LsBottomView.SKIP_TYPE_COUNT_DOWN,status);
        ls_bottom_view.seekBarSetMax(mTimeCount);

        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
        mHandler.sendEmptyMessage(ListenSpeakUtil.HandlerWhat.UPDATE_TIME);

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                int height = question_layout.llStemContainer.getHeight();
                container.smoothScrollTo(0, height);
            }
        });

    }


    private void startLoadChildQuestion(ResourceDetail resourceDetail, String uuid) {

        if (mSmallQuesIndex < resourceDetail.getQuestions().size()) {
            List<Questions> smallQuesList = resourceDetail
                    .getQuestions();
            Questions smallQuestion = smallQuesList.get(mSmallQuesIndex);
            List<Questions> childQuesList = smallQuestion.getChildren();
            if (childQuesList != null && !childQuesList.isEmpty()) {
                for (int i = 0; i < childQuesList.size(); i++) {
                    mChildQuesIndex = i;
                    mQuesTotalIndex++;
                    bigQuesIndex = resourceDetail.getIndex() + 1;
                    totalQuesIndex = mQuesTotalIndex;
                    if (mChildQuesIndex == -1) {
                        quesNo = (bigQuesIndex) + "." + (mSmallQuesIndex + 1);
                    } else {
                        quesNo = (bigQuesIndex) + "." + (mSmallQuesIndex + 1) + "." + (mChildQuesIndex + 1);
                    }
                    question_layout.setChildContent(resourceDetail, smallQuestion, childQuesList.get(mChildQuesIndex), mChildQuesIndex, uuid, mHasDoneAnswers, childQuesList.size(), bigQuesIndex, totalQuesIndex, quesNo);
                }
            }

        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//		AudioPlayer.getInstance().stop();
//		AudioPlayer.getInstance().release();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        if (mRecorderHandler != null) {
            mRecorderHandler.removeCallbacksAndMessages(null);
        }
    }

    protected void printState() {
//		getCaller();
    }

    public void getCaller() {
        StackTraceElement stack[] = (new Throwable()).getStackTrace();
        if (stack.length > 3) {
            Log.e(TAG, " state：" + status + "        getCaller: " + stack[2].getMethodName() + "  " + stack[3].getMethodName());
        }

    }

    /**
     * 开始答题
     */
    protected void startAnswerQuestion() {
        try {
            status = ListenSpeakUtil.State.ANSWER;
            //允许选择题开始答题
            question_layout.allowAnswer(true);
            printState();
            // 进入答题状态
            AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_START_ANSWER, this, null);
        } catch (NullPointerException e) {
            Log.e(TAG, "startAnswerQuestion: Exception");
        }
    }

    protected void startAnswerTimeCount() {
        //录音倒计时
        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
        mHandler.sendEmptyMessage(ListenSpeakUtil.HandlerWhat.UPDATE_TIME);
    }


    /**
     * 自动切换到下一题
     *
     * @param
     */
    protected void autoSwitchNextQuestion(ResourceDetail resourceDetail) {
        ls_bottom_view.microRecordingSetVisibility(View.GONE);
        startSwitchNextQuestion(resourceDetail);
    }

    /**
     * 开始切换到下一题
     */
    protected void startSwitchNextQuestion(ResourceDetail resourceDetail) {
        //当前层级是否有子题，子题遍历，是否有小题，小题是否遍历完，大题遍历
        if (isFinishing()) {
            return;
        }
        List<Questions> smallQuesList = resourceDetail.getQuestions();
        if (smallQuesList != null && mSmallQuesIndex < smallQuesList.size() - 1) {// 下一小题
            loadSwitchAnim();
            mSmallQuesIndex++;
            mChildQuesIndex = 0;
            Questions smallQues = smallQuesList.get(mSmallQuesIndex);
            if (!ListenSpeakUtil.questionTypeIsExist(smallQues.getType())) {
                showToastError(R.string.question_type_not_exist);
                startSwitchNextQuestion(mResourceDetail);
                return;
            }

            question_layout.changeQuestionTitle(mBigQuesIndex, mSmallQuesIndex);
            //选择题取当前的小题序号  拼接 显示   老的资源不支持
            String textTitle;
            String textScore = ListenSpeakUtil.getChildQuestionScore(smallQues, resourceDetail.getScores());
            if (smallQues.getSort() != null && !"".equals(smallQues.getSort())) {
                textTitle = smallQues.getSort() + "、" + textScore + smallQues.getTrunk().getBody();
            } else {
                textTitle = smallQues.getTrunk().getBody();
                if (!"".equals(textTitle)) {
                    if (!"".equals(textScore)) {
                        StringBuffer stringBuffer = new StringBuffer(textTitle);
                        stringBuffer.insert(2, textScore);
                        textTitle = stringBuffer.toString();
                    }
                } else {
                    textTitle = textScore;
                }
            }
            question_layout.setSmallQuestionStem(textTitle);
            onBigStemPlayOver();

        } else {
            if (isFinishing()) {
                return;
            }
            //当前答题做完
            ls_bottom_view.hideTimerAnimation(status);
            if (mLsMode != ListenSpeakUtil.LsMode.RETRY_MODE && mBigQuesIndex == mTotalCount - 1) {
                status = ListenSpeakUtil.State.END;
                AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_END_EXAM, this, null);
            } else {
                setResultAnswer(getConversitionAnswer(), mBigQuesIndex + 1, false, false, true, totalQuesIndex);
            }
        }

    }

    /**
     * 加载切换动画
     */
    protected void loadSwitchAnim() {
        question_layout.optionsLayoutRemoveAllViews();
        container.startAnimation(AnimationUtils.loadAnimation(LongConversationActivity.this, R.anim.right_enter));
        question_layout.reSetCheckedIndex(-1);
    }

    @Override
    public ArrayList<LswAnswer> getConversitionAnswer() {
        ArrayList<LswAnswer> lswAnswers = question_layout.getLswAnswersOfSamllQuestions();
        if (lswAnswers.size() <= 0) {
            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "返回的lswAnswerArrayList为null", "长对话页面" + mLsMode);
        }
        return lswAnswers;
    }


}
